﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using BasicFramework.Devices;
using BasicFramework.Rendering.Buffer;
using BasicFramework.Rendering.Primitives.Indexes;
using BasicFramework.Rendering.Primitives.Vertizes;
using BasicFramework.Services.MeshLoader.Nodes;
using SlimDX;
using SlimDX.Direct3D10;
using SlimDX.Direct3D9;
using BasicFramework.Devices.DirectX9;

namespace BasicFramework.Services.MeshLoader.Meshes
{
    class TexturedMesh : Mesh
    {

        #region Fields



        #endregion


        #region Properties

        #endregion


        #region Constructors

        public TexturedMesh(MeshContainer container, DeviceContextBase context)
            : base(container, context)
        {
            this.Position = container.Position;
            this.ObjectMatrix = container.ObjectMatrix;

            this.WorldMatrix = this.ObjectMatrix * Matrix.Translation(this.Position);
        }

        #endregion


        #region Events

        #endregion


        #region Methods

        public override void LoadTextures(MeshContainer m)
        {
            //Extend this system to a list of textures if you want multitexturing
            if (m.Textures.Count > 1)
            {
                System.Console.WriteLine("Only 1 Texture per mesh supported, try a simpler mesh!");
            }

            foreach (string s in m.Textures)
            {
                this.Context.SetTexture(m.BasePath+ "\\" + s);
            }
        }

        public override void LoadVertexBuffer(MeshContainer m)
        {
            this.VerticeCount = m.Vertices.Count;

            foreach (SkinnedTangentVertex i in m.Vertices)
            {
                this.VertexBuffer.Add(new TexturedVertex(new Vector3(i.pos.X, i.pos.Z, i.pos.Y), new Vector2(i.U, i.V)));
            }

            this.VertexBuffer.Commit();
        }

        public override void LoadIndexBuffer(MeshContainer m)
        {

            this.IndexCount = m.Indices.Length;

            for (int i = 0; i < m.Indices.Length; i++)
            {
                this.IndexBuffer.Add(new Index((short)m.Indices[i]));
            }

            this.IndexBuffer.Commit();

        }

        public override void Render()
        {
            this.IndexBuffer.SetBuffer(0);
            this.VertexBuffer.SetBuffer(0);

            this.Context.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, this.VerticeCount, 0, this.IndexCount / 3);

        }

        #endregion



    }
}
